<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="资料编号" prop="materialNumber">
        <el-input v-model="formData.materialNumber" placeholder="请输入资料编号" disabled />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="formData.productNumber"
          placeholder="请输入产品编号"
          :disabled="formType == 'update'"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="formData.productName"
          placeholder="请输入产品名称"
          :disabled="formType == 'update'"
        />
      </el-form-item>
      <el-form-item label="上传部门" prop="configOrgDeptArchivesId">
        <el-select
          v-model="formData.configOrgDeptArchivesId"
          placeholder="请输入搜索部门"
          filterable
          remote
          reserve-keyword
          :remote-method="getSelectDeptList"
          :loading="deptLoading"
          class="!w-220px"
        >
          <el-option v-for="dict in deptList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="资料名称" prop="materialName">
        <el-input v-model="formData.materialName" placeholder="请输入资料名称" />
      </el-form-item>
      <el-form-item label="资料类型" prop="dictMaterialType">
        <el-select v-model="formData.dictMaterialType" placeholder="请选择资料类型">
          <el-option
            v-for="dict in getIntDictOptions('order_material_type')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="附件">
        <UploadFile
          v-model="fileList"
          :limit="1"
          :fileSize="200"
          :fileType="['pdf', 'png', 'jpg']"
          @update:modelValue="uploadFileRes"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="状态" prop="dictEnableStatus">
        <el-select v-model="formData.dictEnableStatus" placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions('dict_enable_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="_close">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
   import { getIntDictOptions } from '@/utils/dict'
   import * as MaterialInfoApi from '@/api/orderManagement/materialInfo'

   const { t } = useI18n() // 国际化
   const message = useMessage() // 消息弹窗
   import * as componentApi from '@/api/componentApi'
   const dialogVisible = ref(false) // 弹窗的是否展示
   const dialogTitle = ref('') // 弹窗的标题
   const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
   const formType = ref('') // 表单的类型：create - 新增；update - 修改
   const formData = ref({
     id: undefined,
     materialNumber: undefined,
     productNumber: undefined,
     productName: undefined,
     configOrgDeptArchivesId: undefined,
     materialName: undefined,
     filePath: '',
     remark: undefined,
     dictEnableStatus: undefined,
     dictMaterialType: undefined,
     fileName: undefined
   })
   const fileList = ref([])
   const formRules = reactive({
     materialNumber: [{ required: true, message: '资料编号不能为空', trigger: 'blur' }],
     productNumber: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
     productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
     configOrgDeptArchivesId: [{ required: true, message: '上传部门不能为空', trigger: 'change' }],
     materialName: [{ required: true, message: '资料名称不能为空', trigger: 'blur' }],
     dictEnableStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
   })
   const formRef = ref() // 表单 Ref

   /** 打开弹窗 */
   const open = async (type: string, id?: number) => {
     dialogVisible.value = true
     dialogTitle.value = t('action.' + type)
     formType.value = type
     resetForm()
     // 修改时，设置数据
     if (id) {
       formLoading.value = true
       try {
         formData.value = await MaterialInfoApi.getMaterialInfo(id)
         if (formData.value.fileName != '') {
           fileList.value.push({
             name: formData.value.fileName,
             url: formData.value.filePath
           })
         }
       } finally {
         formLoading.value = false
       }
     } else {
       try {
         //获取资料编号
         formData.value = await MaterialInfoApi.getDocumentNumber()
       } finally {
         formLoading.value = false
       }
     }
     getSelectDeptList(formData.value.configOrgDeptArchivesName)
   }
   defineExpose({ open }) // 提供 open 方法，用于打开弹窗
   /**文件上传返回 */
   const uploadFileRes = (data) => {
     console.log(JSON.parse(data))
     if (JSON.parse(data).length) {
       const res = JSON.parse(data)
       formData.value.fileName = res[0].name
       formData.value.filePath = res[0].url
     } else {
       fileList.value = []
       formData.value.fileName = ''
       formData.value.filePath = ''
     }
   }

   /** 提交表单 */
   const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
   const submitForm = async () => {
     // 校验表单
     if (!formRef) return
     const valid = await formRef.value.validate()
     if (!valid) return
     const data = formData.value as unknown as MaterialInfoApi.MaterialInfoVO
     if (data.configOrgDeptArchivesId) {
       data.configOrgDeptArchivesName = deptList.value.filter(
         (item) => item.id == data.configOrgDeptArchivesId
       )[0].name
     }

     if ([null, '', undefined].includes(data.fileName)) {
       message.error('请上传附件')
       return
     }
     // 提交请求
     formLoading.value = true
     try {
      await MaterialInfoApi.updateMaterialInfo(data)
       if (formType.value === 'create') {
         message.success(t('common.createSuccess'))
       } else {
         
         message.success(t('common.updateSuccess'))
       }
       _close()
       // 发送操作成功的事件
       emit('success')
     } finally {
       formLoading.value = false
     }
   }
   /**获取部门列表 */
   const deptList = ref([])
   const deptLoading = ref(false)
   const getSelectDeptList = async (keyword) => {
     deptLoading.value = true
     deptList.value = await componentApi.getDeptList(keyword)
     deptLoading.value = false
   }
   /** 重置表单 */
   const resetForm = () => {
     formData.value = {
       id: undefined,
       materialNumber: undefined,
       productNumber: undefined,
       productName: undefined,
       configOrgDeptArchivesName: undefined,
       materialName: undefined,
       filePath: '',
       remark: undefined,
       dictEnableStatus: undefined,
       dictMaterialType: undefined,
       fileName: undefined
     }
     formRef.value?.resetFields()
   }

   /**关闭 */
   const _close = () => {
     fileList.value = []
     resetForm()
     dialogVisible.value = false
   }
</script>
